<template>
  <Page class="bg-[#f5f5f5] min-h-screen">
    <PageHeader title="收入提现明细" :showBack="true" />
    
    <!-- Tab切换 -->
    <view class="bg-white px-[32rpx] py-[24rpx]">
      <view class="flex bg-[#f5f5f5] rounded-[16rpx] p-[4rpx]">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="flex-1 text-center py-[16rpx] rounded-[12rpx] text-[28rpx] font-medium transition-all duration-200"
          :class="activeTab === index ? 'bg-white text-[#165DFF] shadow-sm' : 'text-[#666]'"
          @click="activeTab = index"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <!-- <view class="bg-white mx-[24rpx] mt-[24rpx] rounded-[24rpx] p-[32rpx] shadow-sm">
      <view class="text-center">
        <text class="text-[26rpx] text-[#666] block mb-[12rpx]">
          {{ activeTab === 0 ? '累计收入' : '累计提现' }}
        </text>
        <text class="text-[40rpx] font-bold text-[#165DFF]">
          ¥{{ activeTab === 0 ? totalIncome : totalExpense }}
        </text>
      </view>
    </view> -->

    <!-- 列表内容 -->
    <view class="mx-[24rpx] mt-[24rpx]">
      <view v-if="loading" class="flex justify-center items-center h-[200rpx]">
        <view class="text-[28rpx] text-[#999]">加载中...</view>
      </view>
      
      <view v-else-if="currentList.length === 0" class="bg-white rounded-[24rpx] p-[80rpx] text-center">
        <view class="text-[28rpx] text-[#999] mb-[16rpx]">暂无记录</view>
        <view class="text-[24rpx] text-[#ccc]">
          {{ 
            activeTab === 0 ? '还没有收入记录' : 
            activeTab === 1 ? '还没有支出记录' : 
            activeTab === 2 ? '还没有提现记录' : 
            '还没有提现记录' 
          }}
        </view>
      </view>
      
      <view v-else class="space-y-[16rpx]">
        <view
          v-for="(item, index) in currentList"
          :key="index"
          class="bg-white rounded-[24rpx] p-[32rpx] shadow-sm"
        >
          <view class="flex justify-between items-start mb-[16rpx]">
            <view class="flex items-center gap-4">
              <view class="text-[30rpx] font-bold text-[#222] mb-[8rpx]">
                {{ item.title }}
              </view>
              <!-- 提现记录显示状态 -->
              <view v-if="activeTab === 2" class="text-[24rpx] text-[#666] mb-[8rpx]">
                <text v-if="item.package_info == 0" class="text-[#999]">(待审核)</text>
                <nut-button size="small" type="primary" v-else @click="handleClaim(item)">去领取</nut-button>
              </view>
            </view>
            <view class="text-right">
              <view class="text-[32rpx] font-bold mb-[8rpx]"
                    :class="activeTab === 0 ? 'text-green-500' : 'text-red-500'">
                {{ activeTab === 0 ? '+' : '-' }}¥{{ item.amount }}
              </view>
            </view>
          </view>
          
          <view class="flex justify-between items-center text-[24rpx] text-[#999] mb-[16rpx]">
            <text>{{ item.time }}</text>
            <text>订单号：{{ item.orderNo }}</text>
          </view>
          
          <!-- 提现记录操作按钮 -->
          <view v-if="activeTab === 3" class="flex justify-end">
            <nut-button
              v-if="item.canClaim"
              size="small"
              type="primary"
              class="bg-[#165DFF] text-white rounded-[20rpx] px-[24rpx] py-[8rpx] text-[24rpx]"
              @click="handleClaim(item)"
            >
              去领取
            </nut-button>
            <view
              v-else
              class="bg-[#f5f5f5] text-[#999] rounded-[20rpx] px-[24rpx] py-[8rpx] text-[24rpx]"
            >
              {{ item.status }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部加载状态 -->
    <view v-if="currentList.length > 0" class="text-center py-[32rpx]">
      <view v-if="loadingMore" class="text-[28rpx] text-[#999]">
        <view class="inline-flex items-center">
          <view class="w-[20rpx] h-[20rpx] border-2 border-[#165DFF] border-t-transparent rounded-full animate-spin mr-[12rpx]"></view>
          正在加载更多...
        </view>
      </view>
      <view v-else-if="!hasMore && currentList.length > 0" class="text-[24rpx] text-[#ccc]">
        <view class="flex items-center justify-center">
          <view class="w-[60rpx] h-[1rpx] bg-[#ddd] mr-[16rpx]"></view>
          <text>没有更多数据了</text>
          <view class="w-[60rpx] h-[1rpx] bg-[#ddd] ml-[16rpx]"></view>
        </view>
      </view>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import Taro from '@tarojs/taro';
import { post } from '@/utils/request';
import PageHeader from '@/components/PageHeader.vue';
import { showToast } from '@tarojs/taro';

// 微信支付相关类型声明
declare global {
  interface Window {
    wx: any;
    WeixinJSBridge: any;
  }
}

const wx = (window as any).wx;
const WeixinJSBridge = (window as any).WeixinJSBridge;

/**
 * 收入提现明细页面
 * @description 显示收入、提现记录列表，支持分页加载
 * @performance 虚拟滚动优化，分页加载减少内存占用
 */

const tabs = [
  { name: '收入', key: 'income', type: 0 },
  { name: '支出', key: 'expense', type: 1 },
  { name: '提现', key: 'cash', type: 3 },
  // { name: '提现记录', key: 'cashRecord', type: 4 }
];

const activeTab = ref(0);
const loading = ref(true);
const loadingMore = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = 10;
const totalCount = ref(0); // 总记录数

// 统计数据
const totalIncome = ref('0.00');
const totalExpense = ref('0.00');

// 列表数据
const incomeList = ref<any[]>([]);
const expenseList = ref<any[]>([]);
const cashList = ref<any[]>([]);
const cashRecordList = ref<any[]>([]);

// 当前显示的列表
const currentList = computed(() => {
  switch (activeTab.value) {
    case 0:
      return incomeList.value;
    case 1:
      return expenseList.value;
    case 2:
      return cashList.value;
    case 3:
      return cashRecordList.value;
    default:
      return incomeList.value;
  }
});

/**
 * 加载数据
 */
const loadData = async (isLoadMore = false) => {
  if (isLoadMore) {
    loadingMore.value = true;
  } else {
    loading.value = true;
    page.value = 1;
  }

  try {
    // 调用接口获取资产记录
    const currentType = tabs[activeTab.value].type;
    const res = await post('/my/assetRecord', {
      type: currentType,
      pageNo: page.value,
      pageSize: pageSize
    });

    console.log('资产记录接口返回:', res);

    if (res.code === 0) {
      const { columns } = res.data;
      
      // 更新总记录数
      totalCount.value = columns.sumamount || 0;
      
      // 格式化数据
      const formattedRecords = columns.records.map((obj: any) => {
        const item = obj.columns;
        return {
          ...item,
          title: item.title || item.remark || '资产记录',
          description: item.detail,
          amount: item.amount || '0.00',
          status: item.status === 1 ? '已完成' : item.status === 0 ? '处理中' : '失败',
          time: item.create_time || item.update_time || '',
          orderNo: item.out_trade_no || item.id || ''
        }
      });
      // 根据当前tab更新对应的列表数据
      if (activeTab.value === 0) {
        if (isLoadMore) {
          incomeList.value.push(...formattedRecords);
        } else {
          incomeList.value = formattedRecords;
        }
        totalIncome.value = (res.data.totalIncome || '0.00').toString();
      } else if (activeTab.value === 1) {
        if (isLoadMore) {
          expenseList.value.push(...formattedRecords);
        } else {
          expenseList.value = formattedRecords;
        }
        totalExpense.value = (res.data.totalExpense || '0.00').toString();
      } else if (activeTab.value === 2) {
        if (isLoadMore) {
          cashList.value.push(...formattedRecords);
        } else {
          cashList.value = formattedRecords;
        }
      } else if (activeTab.value === 3) {
        // 提现记录特殊处理
        const cashRecordData = formattedRecords.map((item: any) => ({
          ...item,
          status: item.status === 1 ? '待领取' : item.status === 2 ? '已领取' : '失败',
          canClaim: item.status === 1, // 可以领取的状态
          claimData: item.claimData || null // 领取相关数据
        }));
        
        if (isLoadMore) {
          cashRecordList.value.push(...cashRecordData);
        } else {
          cashRecordList.value = cashRecordData;
        }
      }

      // 更新分页状态 - 使用总记录数判断是否还有下一页
      const currentListLength = currentList.value.length;
      hasMore.value = currentListLength < totalCount.value;
      if(formattedRecords.length < pageSize){
        hasMore.value = false;
      }
      
      console.log('分页状态:', {
        currentListLength,
        totalCount: totalCount.value,
        hasMore: hasMore.value,
        page: page.value
      });
      
      if (hasMore.value) {
        page.value++;
      }
    } else {
      showToast({ title: res.message || '获取数据失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取资产记录失败:', error);
    showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

/**
 * 加载更多
 */
const loadMore = () => {
  if (!hasMore.value || loadingMore.value) return;
  loadData(true);
};

/**
 * 触底自动加载
 */
const onReachBottom = () => {
  if (hasMore.value && !loadingMore.value && !loading.value) {
    loadMore();
  }
};

/**
 * Tab切换处理
 */
const handleTabChange = () => {
  if (activeTab.value === 0 && incomeList.value.length === 0) {
    loadData();
  } else if (activeTab.value === 1 && expenseList.value.length === 0) {
    loadData();
  } else if (activeTab.value === 2 && cashList.value.length === 0) {
    loadData();
  } else if (activeTab.value === 3 && cashRecordList.value.length === 0) {
    loadData();
  }
};

// 监听Tab切换
watch(activeTab, handleTabChange);

// 下拉刷新处理
const onPullDownRefresh = async () => {
  try {
    await loadData(); // 重新获取数据
    showToast({ title: '刷新成功', icon: 'success' });
  } catch (error) {
    console.error('下拉刷新失败:', error);
    showToast({ title: '刷新失败，请重试', icon: 'none' });
  } finally {
    Taro.stopPullDownRefresh();
  }
};

/**
 * 微信支付确认收款
 * @param item 提现记录项
 */
const handleWechatPayment = (item: any) => {
  Taro.showToast({ title: '提现中...', icon: 'none' });

  (window as any).WeixinJSBridge.invoke('requestMerchantTransfer', {
      mchId: '1724500515',
      appId: 'wxd2a505183cc8e9d3',
      package: item.package_info,
    },
    function (res: any) {
      if (res.err_msg === 'requestMerchantTransfer:ok') {
        showToast({ title: '收款成功', icon: 'success' });
        // 更新本地状态
        // 刷新数据();
        loadData();
      } else {
        showToast({ title: '收款失败，请重试', icon: 'none' });
      }
    }
  );
};

/**
 * 处理去领取按钮点击
 * @param item 提现记录项
 */
const handleClaim = (item: any) => {
  console.log("item", item);
  handleWechatPayment(item);
};

// 注册下拉刷新和触底加载
Taro.usePullDownRefresh(onPullDownRefresh);
Taro.useReachBottom(onReachBottom);

onMounted(() => {
  loadData();
});
</script> 